import request from '@/utils/request'

// const token = 'Bearer ragflow-YzYWVkNzE0Zjg5MDExZWZiYThjMDI0Mm'
const token = 'Bearer ragflow-I5ZjNkODYwMDBjMTExZjA4MmU1MDI0Mm'

const uri = 'http://124.130.192.24:10059'
// const uri = 'http://192.168.0.200:80'
// Bearer ragflow-ZhZjYzNzEyZmFmYTExZWY5OGNkMDI0Mm
// let token = ''
// 列出聊天助手的会话
// export function setToken(data) {
//   token = 'Bearer ragflow-' + data
// }
export function getDialogList(chatId) {
  // console.log(token)
  return request({
    url: uri + `/api/v1/chats/${chatId}/sessions?page=1&page_size=30&orderby=create_time&desc=true}`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'get'
  })
}
// 获取当前聊天会话
export function getMsgList(chatId,sessionId) {
  return request({
    url: uri + `/api/v1/chats/${chatId}/sessions?page=1&page_size=30&desc=true&id=${sessionId}`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'get'
  })
}

/**
 * 聊天
 * @param chatId
 * @param body
 * @returns {AxiosPromise}
 */
export function completions(chatId,body) {
  return request({
    url: uri + `/api/v1/chats/${chatId}/completions`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'post',
    data: body,
    responseType: 'stream'
  })
}

/**
 * 聊天
 * @param {string} chatId - 聊天 ID
 * @param {object} body - 请求体
 * @param {function} onData - 接收到数据时的回调函数
 * @param {function} onError - 错误处理回调函数
 * @param {function} onComplete - 流式传输完成时的回调函数
 */
export function completionsLine(chatId, body, onData, onError, onComplete) {
  fetch(uri + `/api/v1/chats/${chatId}/completions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token, // 替换为实际的 token
    },
    body: JSON.stringify(body),
  })
    .then(response => {
      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8'); // 解码流数据

      function read() {
        reader.read()
          .then(({ done, value }) => {
            if (done) {
              onComplete?.(); // 流式传输完成
              return;
            }
            const chunk = decoder.decode(value, { stream: true }); // 解码分块数据
            onData?.(chunk); // 将数据传递给回调函数
            read(); // 继续读取下一块数据
          })
          .catch(error => {
            onError?.(error); // 处理错误
          });
      }

      read(); // 开始读取流数据
    })
    .catch(error => {
      onError?.(error); // 处理初始请求错误
    });
}
/**
 * 新增会话
 * @param chatId
 * @param body
 * @returns {AxiosPromise}
 */
export function addSession(chatId, body) {
  return request({
    url: uri + `/api/v1/chats/${chatId}/sessions`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'post',
    data: body
  })
}


/**
 * 修改会话
 * @param chatId
 * @param body
 * @returns {AxiosPromise}
 */
export function editSession(chatId,sessionId, body) {
  return request({
    url: uri + `/api/v1/chats/${chatId}/sessions/${sessionId}`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'put',
    data: body
  })
}
/**
 * 删除会话
 * @param chatId
 * @param body
 * @returns {AxiosPromise}
 */
export function delSession(chatId, body) {
  return request({
    url: uri + `/api/v1/chats/${chatId}/sessions`,
    headers: {
      'Authorization': token
    },
    method: 'delete',
    data: body
  })
}

/**
 * 文件列表
 * @param datasetId
 * @param pageNum
 * @param pageSize
 * @param keywords
 * @returns {AxiosPromise}
 */
export function getDataList(datasetId,pageNum,pageSize,keywords) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/documents?page=${pageNum}&page_size=${pageSize}&orderby=create_time&desc=true&keywords=${keywords}`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'get',
  })
}


/**
 * 上传文件
 * @param datasetId
 * @param documentId
 * @param fileBody
 * @returns {AxiosPromise}
 */
export function addFile(datasetId,formData) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/documents`,
    headers: {
      'Authorization': token
    },
    method: 'post',
    data: formData
  })
}

/**
 * 更改文件
 * @param datasetId
 * @param documentId
 * @param fileBody
 * @returns {AxiosPromise}
 */
export function editFile(datasetId,documentId,fileBody) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/documents/${documentId}`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'put',
    data: fileBody
  })
}


/**
 * 解析文件
 * @param datasetId
 * @param documentId
 * @returns {AxiosPromise}
 */
export function parseFile(datasetId,documentId) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/chunks`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'post',
    data: {
      "document_ids": documentId
    }
  })
}
/**
 * 停止解析文件
 * @param datasetId
 * @param documentId
 * @returns {AxiosPromise}
 */
export function stopParseFile(datasetId,documentId) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/chunks`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'delete',
    data: {
      "document_ids": documentId
    }
  })
}

/**
 * 删除文件
 * @param datasetId
 * @param ids
 * @returns {AxiosPromise}
 */
export function delFile(datasetId,ids) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/documents`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'delete',
    data: {
      ids: ids
    }
  })
}

/**
 * 下载文件
 * @param {string} url - 文件下载地址
 * @param {object} params - 请求参数
 * @param {string} filename - 下载的文件名
 */
export function downloadFile(datasetId, id, filename) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/documents/${id}`,
    headers: {
      'Authorization': token
    },
    method: 'get',
    responseType: 'blob'
  })
}


/**
 * 删除数据块
 * @param datasetId
 * @param ids
 * @returns {AxiosPromise}
 */
export function delChunks(datasetId,documentId) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/documents/${documentId}/chunks`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'delete',
  })
}
// 数据集
export function getDataSetList(pageNum,pageSize) {
  return request({
    url: uri + `/api/v1/datasets?page=${pageNum}&page_size=${pageSize}&orderby=create_time&desc=true`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'get',
  })
}
/**
 * 创建聊天助手
 */
export function chatSet(chatSet) {
  return request({
    url: uri + `/api/v1/chats`,
    headers: {
      'Authorization': token
    },
    method: 'post',
    data:chatSet
  })
}

/**
 * 更新聊天助手
 * @param chat_id
 * @param chatSet
 * @returns {AxiosPromise}
 */
export function chatEdit(chat_id,chatSet) {
  return request({
    url: uri + `/api/v1/chats/${chat_id}`,
    headers: {
      'Authorization': token
    },
    method: 'put',
    data:chatSet
  })
}
/**
 * 聊天助手列表
 */
export function chatList(pageNum,pageSize) {
  return request({
    url: uri + `/api/v1/chats?page=${pageNum}&page_size=${pageSize}&orderby=create_time&desc=true`,
    headers: {
      'Authorization': token
    },
    method: 'get',
  })
}

export function dataList(pageNum,pageSize,dataset_id) {
  return request({
    url: uri + `/api/v1/datasets?page=${pageNum}&page_size=${pageSize}&orderby=create_time&desc=true&id=${dataset_id}`,
    headers: {
      'Authorization': token
    },
    method: 'get',
  })
}

//创建知识库
// import axios from 'axios';
//
// const API_BASE_URL = 'https://your-api-endpoint.com/api/v1';
//
// export const createDataset = (payload) => {
//   const token = localStorage.getItem('token'); // 假设 token 存储在 localStorage 中
//   return axios.post(`${API_BASE_URL}/datasets`, payload, {
//     headers: {
//       'Content-Type': 'application/json',
//       'Authorization': `Bearer ${token}`
//     }
//   }).then(response => {
//     return response.data;
//   }).catch(error => {
//     throw error;
//   });
// };

export function createDataset(payload) {
  return request({
    url: uri + '/api/v1/datasets',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'post',
    data: payload // 传递请求体
  });
}


//删除知识库


/**
 * 删除知识库
 * @param {Array<string>} ids - 要删除的知识库 ID 列表
 * @returns {Promise} - 返回一个 Promise，包含 API 响应数据
 */
// export const deleteDataset = (ids) => {
//   const token = localStorage.getItem('token'); // 假设 token 存储在 localStorage 中
//   return axios.delete(`${API_BASE_URL}/datasets`, {
//     headers: {
//       'Content-Type': 'application/json',
//       'Authorization': `Bearer ${token}`
//     },
//     data: { ids } // DELETE 请求的 body
//   })
//     .then(response => {
//       return response.data;
//     })
//     .catch(error => {
//       throw error;
//     });
// };


export function deleteDataset(ids) {
  return request({
    url: uri + '/api/v1/datasets',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'delete',
    data: { ids } // 传递请求体
  });
}

//编辑知识库
export function updateDataset(datasetId, payload) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'put',
    data: payload
  });
}

//搜索知识库

export function search(pageNum, pageSize, keyword = '') {
  return request({
    url: uri + '/api/v1/datasets',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    params: {
      page: pageNum,
      page_size: pageSize,
      orderby: 'create_time',
      desc: true,
      name: keyword // 关键修改：将keyword映射到name参数
    },
    method: 'get',
  })
}

// 获取指定文档中的块
export function getChunks(datasetId, page,pageSize,documentId, keywords, chunkId) {
  return request({
    url: uri + `/api/v1/datasets/${datasetId}/documents/${documentId}/chunks`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    method: 'get',
    params: {
      keywords: keywords,
      page: page,
      page_size: pageSize,
      id: chunkId
    }
  });
}



